﻿using Gl_mes.BLL;
using Gl_mes.BLL.Mes;
using Gl_mes.DAL.MesDB;
using Gl_mes.Tools;
using Gl_mes.View.Dialog.Mes;
using Gl_mes.View.Search;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Sunny.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Vboot.App.K3CloudDataSend;

namespace MesBSW.View.Mes
{
    public partial class ProdSchedulingListFrm : UIPage
    {
        //private MesDB ctx = new MesDB();
        //private BaseControler baseControler = new BaseControler();
        DataTable datadt = new DataTable();
        DataTable gidlddt = new DataTable();
        DataTableTools tableTools = new DataTableTools();
        ProdProcessControler processControler = new ProdProcessControler();
        GetIngredientsListDataFromKdFrm getIngredientsListData = new GetIngredientsListDataFromKdFrm();

        public ProdSchedulingListFrm()
        {
            InitializeComponent();
            PlantPoint.Enabled = false;
            TruePoint.Enabled = false;
            IssueDate.Text = "";
            ProductionDate.Text = "";

            //ArrayList arrayList = new ArrayList();

            //string sql = "select '' id,'' line_name union select id,line_name from prod_line_setting where line_name like '%SMT%' or line_name like '%COB%'";
            //DataTable dt = tableTools.GetDataTable(sql);

            //foreach (DataRow dr in dt.Rows)
            //{
            //    arrayList.Add(new DictionaryEntry(dr[0].ToString(), dr[1].ToString()));
            //    //产线.Items.Add(dr[0]);
            //}

            //产线.DataSource = arrayList;
            //产线.DisplayMember = "value";
            //产线.ValueMember = "key";

            this.uiWaitingBar1.Visible = false;
        }

        private void ProNumber_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                PullingKingDeeDataRuleAndEvent();
            }
        }

        private void PullingKingDeeDataRuleAndEvent()
        {
            if (!string.IsNullOrEmpty(ProNumber.Text) || !string.IsNullOrEmpty(MtoNumber.Text))
            {
                if (string.IsNullOrWhiteSpace(IssueDate.Text))
                {
                    UIMessageTip.Show("请输入发放日期", TipStyle.Orange);
                    return;
                }

                if (string.IsNullOrWhiteSpace(ProductionDate.Text))
                {
                    UIMessageTip.Show("请输入投产日期", TipStyle.Orange);
                    return;
                }

                //if (string.IsNullOrWhiteSpace(产线.Text))
                //{
                //    UIMessageTip.Show("请选择产线", TipStyle.Orange);
                //    return;
                //}

                if (CheckRepeatData())
                {
                    ProNumber.Clear();
                    MtoNumber.Clear();
                    return;
                }

                GetProBillDataToDgv();

                ProNumber.Clear();
                MtoNumber.Clear();
            }
        }

        /// <summary>
        /// 判断是否有重复插入操作
        /// </summary>
        /// <returns></returns>
        private bool CheckRepeatData()
        {
            bool isreapt = false;

            for (int i = 0; i < uiDataGridView1.RowCount - 1; i++)
            {
                if (uiDataGridView1.Rows[i].Cells["单据编码"].Value.ToString() == ProNumber.Text)
                {
                    isreapt = true;
                    UIMessageTip.Show("单据已存在,请勿重复操作！", TipStyle.Orange);
                    //MessageBox.Show("单据已存在,请勿重复操作！");
                }
            }

            //string sql = "select id from prod_line_setting where line_name like 'SMT%'";
            //DataTable dt = tableTools.GetDataTable(sql);

            //string lineid = dt.Rows[0][0].ToString();

            //sql = $"select * from prod_schedule where line_id={lineid} and prod_number='{ProNumber.Text}'";
            //dt = tableTools.GetDataTable(sql);

            //if (dt.Rows.Count > 0)//如果数据库有数据，就不插入
            //{
            //    UIMessageTip.Show($"单据【{ProNumber.Text}】已排单,请勿重复操作！", TipStyle.Orange);
            //    //MessageBox.Show($"单据【{ProNumber.Text}】已排单,请勿重复操作！");
            //    isreapt = true;
            //}

            return isreapt;
        }

        /// <summary>
        /// 根据工单号判断工单是否可排单，如果可排单则显示在dgv
        /// </summary>
        private void GetProBillDataToDgv()
        {
            //string sql = "";
            decimal truepoint = Convert.ToDecimal(TruePoint.Text);
            //string productiondate = "";

            if (datadt.Columns.Count == 0)
            {
                datadt = DgvDataSourceColumnAdd();
            }

            bool isdowork = false;//是否开启异步事务(backgroundWorker1_DoWork)的标识

            string condiStr = $"(fbillno='{ProNumber.Text.Split("-")[0].ToString()}' or F_ABC_Text='{MtoNumber.Text}') and FPRDORGID in ({getIngredientsListData.GetOrganizationID()}) and DateDiff(dd, FCREATEDATE, GetDate()) <= 60 and FDocumentStatus='C'";

            string cols = "fid,fbillno,fmaterialid,fmaterialid.fnumber,fmaterialid.fname,fqty," +
                                   "fmobillno,f_abc_text,f_abc_khdm,f_abc_base.fname,fcreatedate,fapprovedate,fmaterialid.flength,fmaterialid.foldnumber," +
                                   "fmaterialid.fspecification,f_abc_remarks,FBaseUnitID.fname,fmaterialid.fmaterialgroup";

            JArray jArray = GetProBillDataFromKingDee("PRD_PPBOM", condiStr, cols, "fbillno");

            string funit = "";

            foreach (var item in jArray)
            {
                funit = item[16].ToString();
            }

            if (jArray.Count > 0 || getIngredientsListData.FindProductionAccessoryDataFromKingDee(MtoNumber.Text, getIngredientsListData.GetOrganizationID()).Count > 0)//getIngredientsListData.FindProductionAccessoryDataFromKingDee 判断带T工单
            {
                DataTable dt = new DataTable();
                DataTable dt1 = new DataTable();

                if (!string.IsNullOrEmpty(ProNumber.Text))
                {
                    dt = FindDagvDataFromLocalDataTable(funit, $"where a.prod_number = '{ProNumber.Text}'");
                }

                if (!string.IsNullOrEmpty(MtoNumber.Text))
                {
                    dt1 = FindDagvDataFromLocalDataTable(funit, $"where a.mto_number='{MtoNumber.Text}'");
                }

                if (dt.Rows.Count == 0 && dt1.Rows.Count == 0 && !ProNumber.Text.Contains("-"))
                {
                    if (MessageBox.Show("无法查到此单数据,是否拉取数据?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.None) == DialogResult.OK)
                    {
                        gidlddt = getIngredientsListData.GetDataAsDataTable();//从金蝶获取需要插入MES的相关数据

                        isdowork = true;
                        this.ProNumber.ReadOnly = true;
                        this.uiWaitingBar1.Visible = true;
                        backgroundWorker1.RunWorkerAsync();
                        //开始异步事务(backgroundWorker1_DoWork)，插入数据（包括点数数据）

                        UIMessageTip.Show("开始拉取数据，请稍等...", TipStyle.Green);
                    }
                    else
                    {
                        return;
                    }
                }
                else if (dt.Rows.Count == 0 && dt1.Rows.Count == 0 && ProNumber.Text.Contains("-"))
                {
                    UIMessageTip.Show("单据不存在，且不符合从金蝶拉取数据条件！", TipStyle.Orange);
                    return;
                }
                //}

                if (!isdowork)//异步事务(backgroundWorker1_DoWork)内含有给uiDataGridView1.DataSource赋值的步骤，避免重复
                {
                    if (dt.Rows.Count > 0)
                    {
                        SetDataTableData(dt, isdowork, ProductionDate.Text, ref datadt, ref truepoint);//给dt赋数据 
                    }

                    if (dt1.Rows.Count > 0)
                    {
                        SetDataTableData(dt1, isdowork, ProductionDate.Text, ref datadt, ref truepoint);//给dt赋数据
                    }

                    if (datadt.Rows.Count > 0)
                    {
                        TruePoint.Text = truepoint.ToString();
                        uiDataGridView1.DataSource = datadt;
                    }
                }
            }
            else
            {
                UIMessageTip.Show("数据不符合从金蝶拉取数据条件！", TipStyle.Orange);
                return;
            }
        }

        public void SetDataTableData(DataTable dt, bool isdowork, string productiondate, ref DataTable framedt, ref decimal truepoint)
        {
            string sql = "";
            string[] strarr = new string[dt.Columns.Count];
            DataTable dt1 = framedt;

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                strarr[i] = dt.Rows[0][i].ToString();
            }

            string iscpele = "0";

            DataTable materdt = new DataTable();
            DataRow dr = dt1.NewRow();

            decimal orderqty = 0;
            decimal pointscount = 0;
            decimal pcbpointqty = 0;
            decimal orderpointqty = 0;

            dr["fid"] = strarr[0];
            dr["f_abc_khdm"] = strarr[18];
            dr["fmtono"] = strarr[7];
            dr["fmobillno"] = strarr[6];
            dr["fbillno"] = strarr[1];
            dr["fnumber"] = strarr[3];
            dr["foldnumber"] = strarr[13];
            dr["fname"] = strarr[4];
            dr["funit"] = strarr[16];
            dr["fqty"] = strarr[5];
            dr["flength"] = strarr[12];
            dr["fspecification"] = strarr[14];
            dr["businessname"] = strarr[9];
            dr["orderdate"] = strarr[11];
            dr["f_abc_remarks"] = strarr[15];
            dr["fmaterialgroup"] = strarr[17];
            dr["group_name"] = strarr[17];//dt.Rows[0][dt.Columns.Count - 1];

            foreach (var item1 in GetMoBillDataFromKingDee(strarr[6].ToString(), strarr[3].ToString()))
            {
                dr["finishdate"] = Convert.ToDateTime(item1[0]).ToString("yyyy-MM-dd HH:mm:ss");
            }

            //dr["finishdate"] =Convert.ToDateTime(GetMoBillDataFromKingDee(item[6].ToString(), item[3].ToString())[0].ToString()
            //    .Substring(2,19)).ToString("yyyy-MM-dd HH:mm:ss");

            sql = "select * from(" + Environment.NewLine;
            sql += "select c.pointscount*(a.prod_qty/a.order_qty) pointscount,COUNT(pointscount) pcount from target_prod_process a" + Environment.NewLine;
            sql += "left join source_prod_process b on a.parent_id=b.id" + Environment.NewLine;
            sql += "left join prodbill_point c on b.prod_number=c.prod_number" + Environment.NewLine;
            sql += $"where a.prod_number='{dr["fbillno"]}'" + Environment.NewLine;
            sql += "group by c.pointscount*(a.prod_qty/a.order_qty))aaa" + Environment.NewLine;

            dt = tableTools.GetDataTable(sql);

            if (dt != null)
            {
                if (Convert.ToInt32(dt.Rows[0][1]) == 0 && !isdowork)//如果只缺少点数数据，则直接补充
                {
                    MaterialPointsComputeFrm pointsComputeFrm = new MaterialPointsComputeFrm();
                    pointsComputeFrm.PointCountAndGetMaterialDetails(dr["fbillno"].ToString().Split("-")[0], ref orderqty, ref pointscount, ref pcbpointqty, ref orderpointqty, ref materdt);

                    ProdPointSMT prodPointSMT = new ProdPointSMT();
                    MesDB ctx = new MesDB();

                    prodPointSMT.ProdNumber = dr["fbillno"].ToString().Split("-")[0];
                    prodPointSMT.OrderQty = orderqty;
                    prodPointSMT.PointTotal = pointscount;
                    prodPointSMT.PointPCB = pcbpointqty;
                    prodPointSMT.PointUnit = orderpointqty;

                    ctx.ProdPointSMT.Add(prodPointSMT);
                    ctx.SaveChanges();
                }
                else if (Convert.ToInt32(dt.Rows[0][1]) > 0)
                {
                    dr["pointcount"] = Convert.ToDecimal(dt.Rows[0][0]);
                }
            }

            //dr["pointcount"] = pointscount;

            //if (ProductionDate != null)
            //{
            TimeSpan timeSpan = Convert.ToDateTime(productiondate) - Convert.ToDateTime(strarr[11]);

            if (timeSpan.Days < 1)
            {
                iscpele = "1";
            }
            //}

            string billtypename = processControler.JudgeProdRawPM(strarr[3].ToString());

            if (string.IsNullOrEmpty(billtypename))
            {
                billtypename = "内部加工";
            }

            sql = $"select smt_days smt_days from prod_cycle where prod_type='{billtypename}' and is_complete='{iscpele}' " +
               $"and ({Convert.ToDecimal(strarr[5])} between min_qty and max_qty)";

            double smt_time = Convert.ToDouble(tableTools.GetDataTable(sql).Rows[0][0]);

            dr["smt_time"] = smt_time;

            framedt.Rows.Add(dr);

            //if (TruePoint != null)
            //{
            try
            {
                truepoint = (truepoint + Convert.ToDecimal(dr["pointcount"]));
                if (Convert.ToDecimal(truepoint) < 0)
                {
                    truepoint = 0;
                }
            }
            catch { truepoint = 0; }
            //}

            //return dt1;
        }

        public DataTable FindDagvDataFromLocalDataTable(string funit, string wheresql)
        {
            string sql = "select b.id, b.prod_number,'',b.goods_number,b.goods_name,b.prod_qty,b.mo_number,b.mto_number fmtono,'',isnull(b.saler_name,'')businessname," + Environment.NewLine;
            sql += $"'',b.create_date,b.goods_length,isnull(b.old_number,''),b.goods_spe,b.remark,'{funit}',d.group_name,b.client_code,a.mpsbilldate," + Environment.NewLine;
            sql += $"(case when smt_mater_count=0 then '1' when (smt_mater_count-smt_mater_ready_count)>0 then '2' when (smt_mater_count-smt_mater_ready_count)=0 then '3' end)smt_ready_status," + Environment.NewLine;
            sql += $"(case when hj_mater_count=0 then '1' when (hj_mater_count-hj_mater_ready_count)>0 then '2' when (hj_mater_count-hj_mater_ready_count)=0 then '3' end) hj_ready_status," + Environment.NewLine;
            sql += $"(case when bz_mater_count=0 then '1' when (bz_mater_count-bz_mater_ready_count)>0 then '2' when (bz_mater_count-bz_mater_ready_count)=0 then '3' end) bz_ready_status" + Environment.NewLine;
            //sql += $"calculate_date" + Environment.NewLine;
            sql += "from source_prod_process a" + Environment.NewLine;
            sql += "left join target_prod_process b on b.parent_id = a.id" + Environment.NewLine;
            sql += "left join pp_site c on c.pp_id = b.id" + Environment.NewLine;
            sql += "left join site_group d on d.id = c.site_group_id" + Environment.NewLine;
            sql += "left join (select prod_number,sum((case when site_name like 'SMT%' then case when is_ready='true' then 1 else 0 end else 0 end)) smt_mater_ready_count," +
                "sum((case when site_name like 'SMT%' then 1 else 0 end)) smt_mater_count,sum((case when site_name like '焊接%' " +
                "then case when is_ready='true' then 1 else 0 end else 0 end)) hj_mater_ready_count,sum((case when site_name like '焊接%' then 1 else 0 end)) hj_mater_count," +
                "sum((case when site_name like '包装%' then case when is_ready='true' then 1 else 0 end else 0 end)) bz_mater_ready_count,sum((case when site_name like '包装%' " +
                "then 1 else 0 end)) bz_mater_count from material_ready_information a " +
                "left join site_info b on a.site_id = b.id " +
                "group by prod_number)e on b.prod_number = e.prod_number" + Environment.NewLine;
            sql += wheresql;

            DataTable dt = tableTools.GetDataTable(sql);

            return dt;
        }

        public DataTable DgvDataSourceColumnAdd()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("fid");
            dt.Columns.Add("f_abc_khdm");
            dt.Columns.Add("fmtono");
            dt.Columns.Add("fmobillno");
            dt.Columns.Add("fbillno");
            dt.Columns.Add("fnumber");
            dt.Columns.Add("fname");
            dt.Columns.Add("fspecification");
            dt.Columns.Add("funit");
            dt.Columns.Add("fqty");
            dt.Columns.Add("flength");
            dt.Columns.Add("group_name");
            dt.Columns.Add("businessname");
            dt.Columns.Add("pointcount");
            dt.Columns.Add("orderdate");
            dt.Columns.Add("foldnumber");
            dt.Columns.Add("f_abc_remarks");
            dt.Columns.Add("fmaterialgroup");
            dt.Columns.Add("finishdate");
            dt.Columns.Add("smt_time");

            return dt;
        }

        /// <summary>
        /// 从金蝶获取工单数据
        /// </summary>
        /// <returns></returns>
        public JArray GetProBillDataFromKingDee(string formid_kd, string condiStr, string cols, string orderstr)
        {
            List<object> Parameters = new List<object>();

            K3CloudLogin k3CloudLogin = new K3CloudLogin();
            k3CloudLogin.CheckLogin();

            HttpClient httpClient = new HttpClient();
            httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");

            //string condiStr = $"fbillno='{pronumber}' and FPRDORGID in ('100155','100158') and DateDiff(dd, FCREATEDATE, GetDate()) <= 60 and FDocumentStatus='C'";

            //string cols = "fid,fbillno,fmaterialid,fmaterialid.fnumber,fmaterialid.fname,fqty," +
            //                        "fmobillno,f_abc_text,f_abc_khdm,f_abc_base.fname,fcreatedate,fapprovedate,fmaterialid.flength,fmaterialid.foldnumber," +
            //                        "fmaterialid.fspecification,f_abc_remarks,FBaseUnitID.fname,fmaterialid.fmaterialgroup";

            string data = "{\"FormId\":\"" + formid_kd + "\",\"TopRowCount\":0,\"Limit\":0,\"StartRow\":0," +
                                  "\"FilterString\":\"" + condiStr + "\",\"OrderString\":\"" + orderstr + "\"," + "\"FieldKeys\":\"" + cols + "\"}";//获取金蝶生产用料清单数据的报文
            Parameters.Add(data);
            httpClient.Content = JsonConvert.SerializeObject(Parameters);
            var results = httpClient.AsyncRequest();

            JArray jArray = JArray.Parse(results);

            return jArray;
        }

        private void btnDelBill_Click(object sender, EventArgs e)
        {
            //decimal count = 0;//应减去总数
            DataTable dt = datadt.Clone();

            for (int i = 0; i < uiDataGridView1.RowCount - 1; i++)
            {
                if (uiDataGridView1.Rows[i].Cells["选择"].EditedFormattedValue.ToString() != "True")
                {
                    DataRow dr = dt.NewRow();
                    dr["fid"] = uiDataGridView1.Rows[i].Cells["ID"].Value;
                    dr["f_abc_khdm"] = uiDataGridView1.Rows[i].Cells["客户代码"].Value;
                    dr["fmtono"] = uiDataGridView1.Rows[i].Cells["计划跟踪号"].Value;
                    dr["fmobillno"] = uiDataGridView1.Rows[i].Cells["生产订单编号"].Value;
                    dr["fbillno"] = uiDataGridView1.Rows[i].Cells["单据编码"].Value;
                    dr["fnumber"] = uiDataGridView1.Rows[i].Cells["成品编号"].Value;
                    dr["foldnumber"] = uiDataGridView1.Rows[i].Cells["旧料号"].Value;
                    dr["fname"] = uiDataGridView1.Rows[i].Cells["成品名称"].Value;
                    dr["fspecification"] = uiDataGridView1.Rows[i].Cells["规格型号"].Value;
                    dr["funit"] = uiDataGridView1.Rows[i].Cells["单位"].Value;
                    dr["fqty"] = uiDataGridView1.Rows[i].Cells["单据数量"].Value;
                    dr["flength"] = uiDataGridView1.Rows[i].Cells["长度"].Value;
                    dr["businessname"] = uiDataGridView1.Rows[i].Cells["业务员"].Value;
                    dr["group_name"] = uiDataGridView1.Rows[i].Cells["流程组别"].Value;
                    dr["pointcount"] = uiDataGridView1.Rows[i].Cells["订单总点数"].Value;
                    dr["f_abc_remarks"] = uiDataGridView1.Rows[i].Cells["备注"].Value;
                    dr["finishdate"] = uiDataGridView1.Rows[i].Cells["计划完成日期"].Value;
                    dr["smt_time"] = uiDataGridView1.Rows[i].Cells["SMT完成周期"].Value;

                    dt.Rows.Add(dr);
                }
                else
                {
                    TruePoint.Text = (Convert.ToDecimal(TruePoint.Text) - Convert.ToDecimal(uiDataGridView1.Rows[i].Cells["订单总点数"].Value)).ToString();
                }
            }

            datadt = dt;
            uiDataGridView1.DataSource = datadt;
        }

        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            string cfinsertbill = "";//重复插入数据单据名单
            string ebillno = "";
            bool iserorr = false;

            if (datadt.Rows.Count == 0)
            {
                UIMessageBox.ShowWarning($"没有可保存的数据！");
                return;
            }

            for (int i = 0; i < uiDataGridView1.RowCount - 1; i++)
            {
                try
                {
                    string lineid = "";
                    string linecode = "";
                    string linename = "";
                    string lastsiteid = "";

                    string pronumber = uiDataGridView1.Rows[i].Cells["单据编码"].Value.ToString();
                    string maternumber = uiDataGridView1.Rows[i].Cells["成品编号"].Value.ToString();
                    string good_spe = uiDataGridView1.Rows[i].Cells["规格型号"].Value.ToString();

                    DateTime mat_wait_date = DateTime.Now;
                    DateTime smt_date = DateTime.Now;
                    DateTime weld_date = DateTime.Now;
                    DateTime test_date = DateTime.Now;
                    DateTime pack_date = DateTime.Now;
                    DateTime plan_date = DateTime.Now;
                    DateTime proddate = Convert.ToDateTime(ProductionDate.Text);

                    DateTime orderdate = DateTime.Now;

                    if (!string.IsNullOrEmpty(uiDataGridView1.Rows[i].Cells["订单日期"].Value.ToString()))
                    {
                        orderdate = Convert.ToDateTime(uiDataGridView1.Rows[i].Cells["订单日期"].Value);
                    }

                    double err_days = 0;

                    LogHelper.info($"{pronumber}:1");

                    string sqlwhere = "where line_name like '%SMT%'";

                    if (good_spe.Contains("COB"))
                    {
                        sqlwhere = "where line_name like '%COB%'";
                    }

                    //string sql = $"select id,line_code,line_name,last_site_id from prod_line_setting where id = '{产线.SelectedValue}'";
                    string sql = $"select id,line_code,line_name,last_site_id from prod_line_setting {sqlwhere}";

                    DataTable dt = tableTools.GetDataTable(sql);

                    if (dt.Rows.Count > 0)
                    {
                        lineid = dt.Rows[0][0].ToString();
                        linecode = dt.Rows[0][1].ToString();
                        linename = dt.Rows[0][2].ToString();
                        lastsiteid = dt.Rows[0][3].ToString();
                    }

                    LogHelper.info($"{pronumber}:2");

                    string iscpele = "0";//是否齐料              
                    TimeSpan timeSpan = proddate - orderdate;

                    if (timeSpan.Days < 1)
                    {
                        iscpele = "1";
                    }

                    string typename = processControler.JudgeProdRawPM(maternumber);

                    if (string.IsNullOrEmpty(typename))
                    {
                        typename = "内部加工";
                    }

                    LogHelper.info($"{pronumber}:3");

                    sql = $"select mat_wait_days,smt_days,weld_days,test_days,pack_days,err_days " + Environment.NewLine;
                    sql += $"from prod_cycle where ((select prod_qty from target_prod_process where prod_number='{pronumber}') between min_qty and max_qty)" + Environment.NewLine;
                    sql += $"and is_complete={iscpele} and prod_type='{typename}'";
                    DataTable pcdt = tableTools.GetDataTable(sql);

                    if (pcdt.Rows.Count > 0)
                    {
                        mat_wait_date = orderdate.AddMinutes(Convert.ToDouble(pcdt.Rows[0][0]) * 24 * 60);
                        smt_date = mat_wait_date.AddMinutes(Convert.ToDouble(pcdt.Rows[0][1]) * 24 * 60);
                        weld_date = smt_date.AddMinutes(Convert.ToDouble(pcdt.Rows[0][2]) * 24 * 60);
                        test_date = weld_date.AddMinutes(Convert.ToDouble(pcdt.Rows[0][3]) * 24 * 60);
                        pack_date = test_date.AddMinutes(Convert.ToDouble(pcdt.Rows[0][4]) * 24 * 60);
                        plan_date = pack_date.AddMinutes(Convert.ToDouble(pcdt.Rows[0][5]) * 24 * 60);
                        err_days = Convert.ToDouble(pcdt.Rows[0][5]);
                    }

                    LogHelper.info($"{pronumber}:4");

                    sql = $"select id from source_pp_cycle where prod_number='{pronumber}'";
                    DataTable countdt = tableTools.GetDataTable(sql);

                    sql = $"update source_pp_cycle set is_complete={iscpele},mat_wait_date='{mat_wait_date}',smt_date='{smt_date}',weld_date='{weld_date}'," +
                        $"test_date='{test_date}',pack_date='{pack_date}',plan_date='{plan_date}',end_date='{plan_date}',err_days='{err_days}' where prod_number='{pronumber}'";
                    tableTools.ExecuteNonQuery(sql);

                    LogHelper.info($"{pronumber}:5");

                    sql = $"select * from prod_schedule where line_id={lineid} and prod_number='{pronumber}' and is_del='0'";
                    dt = tableTools.GetDataTable(sql);

                    if (dt.Rows.Count == 0)//判断是否有排单数据,没有的话进行数据插入步骤,否则不插入,避免数据重复
                    {
                        string tprodid = "";

                        sql = $"select id from target_prod_process where prod_number='{pronumber}'";
                        dt = tableTools.GetDataTable(sql);

                        if (dt.Rows.Count > 0)
                        {
                            tprodid = dt.Rows[0][0].ToString();
                        }

                        LogHelper.info($"{pronumber}:6");

                        sql = $"select scan_date from pp_scan where prod_number='{pronumber}' and site_id={lastsiteid}";
                        DataTable scandt = tableTools.GetDataTable(sql);

                        string iscomp = "0";//是否完工
                        string codatesql = "comp_date=NULL";
                        string remarksql = "remark='未收到'";

                        if (scandt.Rows.Count > 0)
                        {
                            iscomp = "1";
                            codatesql = $"comp_date='{scandt.Rows[0][0].ToString()}'";
                            remarksql = "remark=NULL";
                        }

                        LogHelper.info($"{pronumber}:7");

                        sql = $"insert into prod_schedule select line_id={lineid},line_code='{linecode}',line_name='{linename}'," +
                            $"fill_date='{IssueDate.Text.Substring(0, 10)}',prod_date='{ProductionDate.Text.Substring(0, 10)}'," +
                            $"prod_id={tprodid},prod_number='{pronumber}',is_comp='{iscomp}',{codatesql},{remarksql},remark_pmc=NULL," +
                            $"remark_bus=NULL,is_del=0,create_user='{MainFrm.LoginUser.user_name}'," +
                            $"create_date='{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}',comp_line_id=0";
                        tableTools.ExecuteNonQuery(sql);

                        LogHelper.info($"{pronumber}:8");

                        sql = $"update target_pp_cycle set mat_wait_date='{IssueDate.Text.Substring(0, 10)}' where prod_number='{pronumber}'";
                        tableTools.ExecuteNonQuery(sql);

                        LogHelper.info($"{pronumber}:9");
                        //LogHelper.info($"完成！单据【{uiDataGridView1.Rows[i].Cells["单据编码"].Value}】已插入！");
                    }
                    else
                    {
                        cfinsertbill += pronumber + ",";
                    }
                }
                catch (Exception ex)
                {
                    iserorr = true;
                    ebillno += uiDataGridView1.Rows[i].Cells["单据编码"].Value.ToString() + ",";
                    LogHelper.error($"单据编号【{uiDataGridView1.Rows[i].Cells["单据编码"].Value}】:" + ex.Message);
                }
            }

            cfinsertbill = cfinsertbill.TrimEnd(',');
            ebillno = ebillno.TrimEnd(',');
            //TruePoint.Text = "0.00";
            //datadt.Rows.Clear();
            if (!iserorr)
            {
                if (cfinsertbill.Length > 0)
                {
                    UIMessageBox.ShowWarning($"完成！单据【{cfinsertbill}】为重复数据，无法插入！");
                }
                else
                {
                    UIMessageBox.ShowSuccess("完成！");
                }
            }
            else { UIMessageBox.ShowWarning($"完成！单据【{ebillno}】保存时出错，无法保存到数据库，详细请查看日志文件！"); }
        }

        /// <summary>
        /// 异步事务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //DataTable dt = getIngredientsListData.GetDataAsDataTable();
            getIngredientsListData.InsertManinBusinessData(gidlddt);
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                this.ProNumber.ReadOnly = false;
                this.uiWaitingBar1.Visible = false;
                uiDataGridView1.DataSource = datadt;
                UIMessageTip.Show("完成！请重新输入单号", TipStyle.Green);
            }
        }

        /// <summary>
        /// 异步程序进行中发生的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //this.uiProcessBar1.Value = e.ProgressPercentage;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            UnlackBillDataDia unlackBillDataDia = new UnlackBillDataDia();
            unlackBillDataDia.ShowDialog();
        }

        //进出界面后弹出相关超期单据信息
        private void ProdSchedulingListFrm_Load(object sender, EventArgs e)
        {
            //SearchRedunProdFrm searchRedunProdFrm = new SearchRedunProdFrm();
            UnlackBillDataDia unlackBillDataDia = new UnlackBillDataDia();
            if (unlackBillDataDia.FindUnSchedulingData().Rows.Count > 0)
            {
                ShowWarningNotifier($"共 {unlackBillDataDia.FindUnSchedulingData().Rows.Count}张工单超期");
            }

            foreach (DataGridViewColumn dgvc in uiDataGridView1.Columns)
            {
                if (dgvc.HeaderText != "选择")
                {
                    dgvc.ReadOnly = true;
                }
            }
        }

        /// <summary>
        /// 导出排单EXCEL按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGoodsErrOutput_Click(object sender, EventArgs e)
        {
            DataOutPutAsExcelEvent();
        }

        private void DataOutPutAsExcelEvent()
        {
            DateTime tmpDay = DateTime.Now;
            string basePath = Application.StartupPath + "\\排单计划";
            string fileName = $"排单计划{DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "")}.xlsx";
            if (this.uiDataGridView1.Rows.Count - 1 > 0)
            {
                DataTable tmpDt = this.uiDataGridView1.DataSource as DataTable;
                if (tmpDt != null && tmpDt.Rows.Count > 0)
                {
                    try
                    {
                        this.OutPutExcel(basePath, fileName, tmpDt);
                        UIMessageBox.ShowSuccess("EXCEL文件已经成功导出！");
                        Process.Start(basePath);
                    }
                    catch (Exception ex)
                    {
                        UIMessageBox.ShowError("导出EXCEL文件失败！" + "\r\n" + ex.Message);
                    }
                }
            }
            else
            {
                UIMessageBox.ShowWarning("没有任何可以导出的资料！");
            }
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        /// <param name="dt"></param>
        private void OutPutExcel(string path, string fileName, DataTable dt)
        {

            if (System.IO.Directory.Exists(path) == false)
            {
                System.IO.Directory.CreateDirectory(path);
            }

            // 创建工作簿对象
            var workbook = new XSSFWorkbook();

            // 创建工作表对象
            var sheet = workbook.CreateSheet("排单计划");

            #region excel格式设置
            var titleStyle = workbook.CreateCellStyle();
            NPOI.SS.UserModel.IFont titleFont = workbook.CreateFont();
            titleFont.IsBold = true;
            titleFont.FontHeightInPoints = 14;
            titleStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            titleStyle.VerticalAlignment = VerticalAlignment.Center;
            titleStyle.WrapText = true;
            titleStyle.SetFont(titleFont);

            var bodyStyle = workbook.CreateCellStyle();
            NPOI.SS.UserModel.IFont matFont = workbook.CreateFont();
            matFont.IsBold = false;
            matFont.FontHeightInPoints = 10;
            bodyStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            bodyStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            bodyStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            bodyStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            bodyStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
            bodyStyle.VerticalAlignment = VerticalAlignment.Top;
            bodyStyle.ShrinkToFit = true;
            //bodyStyle.WrapText = true;
            bodyStyle.SetFont(matFont);

            var qtyStyle = workbook.CreateCellStyle();
            qtyStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.000");
            qtyStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            qtyStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            qtyStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            qtyStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            qtyStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            qtyStyle.VerticalAlignment = VerticalAlignment.Center;
            qtyStyle.ShrinkToFit = true;
            qtyStyle.SetFont(matFont);

            var dateStyle = workbook.CreateCellStyle();
            dateStyle.DataFormat = workbook.CreateDataFormat().GetFormat("yyyy-MM-dd");
            dateStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            dateStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            dateStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            dateStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            dateStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            dateStyle.VerticalAlignment = VerticalAlignment.Center;
            dateStyle.ShrinkToFit = true;
            dateStyle.SetFont(matFont);

            int rowIndex = 0;

            List<string> titles = new List<string>(new string[] { "序号", "业务员", "计划跟踪号", "订单号", "工单单号","客户代码", "主件品号", "型号规格", "订单数量", "单位","产品分类", "生产性质","预计日期",
                "预计完工日期", "SMT备料日期" ,"SMT板号","SMT点数","SMT完成日期","SMT投产数量","备注","长度"});

            List<int> widths = new List<int>(new int[] { 6, 10, 15, 15, 15, 15, 20, 70, 12, 12, 12, 12, 12, 12, 12, 15, 10, 12, 12, 100, 15 });

            for (int i = 0; i < widths.Count; i++)
            {
                sheet.SetColumnWidth(i, widths[i] * 256);
            }

            var titleRow = sheet.CreateRow(rowIndex);

            for (int i = 0; i < titles.Count; i++)
            {
                var titleCell = titleRow.CreateCell(i);
                titleCell.CellStyle = titleStyle;
                titleCell.SetCellValue(titles[i]);
            }
            #endregion

            #region 需要导出的数据
            rowIndex += 1;
            int xuhao = 1;

            if (dt != null && dt.Rows.Count > 0)
            {
                DataRow dr = dt.NewRow();
                dt.Rows.Add(dr);//增加表底合计列
                dr = dt.NewRow();
                dt.Rows.Add(dr);//增加表底建表、审核、批准列

                foreach (DataRow tmpRow in dt.Rows)
                {
                    //string iscpele = "0";//是否齐料
                    //string orderdate = tmpRow["orderdate"].ToString();

                    var bodyRow = sheet.CreateRow(rowIndex);
                    for (int i = 0; i < titles.Count; i++)
                    {
                        var bodyCell = bodyRow.CreateCell(i);
                        if (i == 7 || i == 15)
                        {
                            bodyCell.CellStyle = qtyStyle;
                        }
                        else if (i == 11 || i == 12 || i == 13 || i == 16)
                        {
                            bodyCell.CellStyle = dateStyle;
                        }
                        else
                        {
                            bodyCell.CellStyle = bodyStyle;
                        }
                    }

                    if (xuhao == dt.Rows.Count - 1)
                    {
                        //bodyRow.GetCell(0).SetCellValue("");
                        bodyRow.GetCell(2).SetCellValue("发放日期：");
                        bodyRow.GetCell(3).SetCellValue(IssueDate.Text);
                        bodyRow.GetCell(14).SetCellValue("合计：");
                        bodyRow.GetCell(15).SetCellValue(TruePoint.Text);
                        //bodyRow.GetCell(16).SetCellValue("");
                    }
                    else if (xuhao == dt.Rows.Count)
                    {
                        bodyRow.GetCell(0).SetCellValue("制表：");
                        bodyRow.GetCell(5).SetCellValue("审核：");
                        bodyRow.GetCell(10).SetCellValue("批准：");
                        //bodyRow.GetCell(13).SetCellValue("");
                    }
                    else
                    {
                        bodyRow.GetCell(0).SetCellValue(xuhao);
                        bodyRow.GetCell(1).SetCellValue(tmpRow["businessname"].ToString());
                        bodyRow.GetCell(2).SetCellValue(tmpRow["fmtono"].ToString());
                        bodyRow.GetCell(3).SetCellValue(tmpRow["fmobillno"].ToString());
                        bodyRow.GetCell(4).SetCellValue(tmpRow["fbillno"].ToString());
                        bodyRow.GetCell(5).SetCellValue(tmpRow["f_abc_khdm"].ToString());
                        bodyRow.GetCell(6).SetCellValue(tmpRow["fnumber"].ToString());
                        bodyRow.GetCell(7).SetCellValue(tmpRow["fspecification"].ToString());
                        bodyRow.GetCell(8).SetCellValue(tmpRow["fqty"].ToString());
                        bodyRow.GetCell(9).SetCellValue(tmpRow["funit"].ToString());
                        bodyRow.GetCell(10).SetCellValue("软灯条");//产品分类
                        bodyRow.GetCell(11).SetCellValue(tmpRow["fmaterialgroup"].ToString());
                        bodyRow.GetCell(12).SetCellValue(Convert.ToDateTime(this.IssueDate.Text).ToString("MM/dd"));//预计日期（取发放日期）
                        bodyRow.GetCell(13).SetCellValue(tmpRow["finishdate"].ToString());//预计完工日期
                        bodyRow.GetCell(14).SetCellValue(Convert.ToDateTime(this.IssueDate.Text).ToString("MM/dd"));//备料日期（取发放日期）
                        bodyRow.GetCell(15).SetCellValue(tmpRow["foldnumber"].ToString());
                        bodyRow.GetCell(16).SetCellValue(tmpRow["pointcount"].ToString());
                        bodyRow.GetCell(17).SetCellValue(Convert.ToDateTime(ProductionDate.Value).AddDays(Convert.ToDouble(tmpRow["smt_time"]) == 0 ? 0 : Convert.ToDouble(tmpRow["smt_time"]) - 1).ToString("MM/dd"));
                        bodyRow.GetCell(18).SetCellValue(tmpRow["fqty"].ToString());
                        bodyRow.GetCell(19).SetCellValue(tmpRow["f_abc_remarks"].ToString());
                        bodyRow.GetCell(20).SetCellValue(tmpRow["flength"].ToString());
                    }

                    xuhao++;
                    rowIndex++;
                }
            }
            #endregion

            // 保存工作簿到文件
            using (var fileStream = new FileStream(path + "\\" + fileName, FileMode.Create))
            {
                workbook.Write(fileStream);
            }

            // 清除空白行
            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                DataRow row = dt.Rows[i];
                bool isRowEmpty = true;

                foreach (var item in row.ItemArray)
                {
                    if (!string.IsNullOrWhiteSpace(item.ToString()))
                    {
                        isRowEmpty = false;
                        break;
                    }
                }

                if (isRowEmpty)
                {
                    dt.Rows.RemoveAt(i);
                }
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            TruePoint.Text = "0.00";
            datadt.Rows.Clear();
        }

        public JArray GetMoBillDataFromKingDee(string monumber, string fnumber)
        {
            List<object> Parameters = new List<object>();

            K3CloudLogin k3CloudLogin = new K3CloudLogin();
            k3CloudLogin.CheckLogin();

            HttpClient httpClient = new HttpClient();
            httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");

            string condiStr = $"fbillno='{monumber}' and fmaterialid.fnumber ='{fnumber}'";

            string cols = "FPlanFinishDate,FAPPROVEDATE";

            string data = "{\"FormId\":\"PRD_MO\",\"TopRowCount\":0,\"Limit\":0,\"StartRow\":0," +
                                  "\"FilterString\":\"" + condiStr + "\",\"OrderString\":\"fbillno\"," + "\"FieldKeys\":\"" + cols + "\"}";//获取金蝶生产用料清单数据的报文
            Parameters.Add(data);
            httpClient.Content = JsonConvert.SerializeObject(Parameters);
            var results = httpClient.AsyncRequest();

            JArray jArray = JArray.Parse(results);

            return jArray;
        }

        private void uiDataGridView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.uiDataGridView1.ShowContextMenuStrip(this.uiContextMenuStrip1, e.Location);
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (this.uiDataGridView1.Rows.Count > 0 && this.uiDataGridView1.SelectedCells.Count > 0)
            {
                DataRow tmpRow = (this.uiDataGridView1.Rows[this.uiDataGridView1.SelectedCells[0].RowIndex].DataBoundItem as DataRowView).Row;
                string tmpProd = "";
                if (tmpRow != null && tmpRow.Table.Columns.Contains("fbillno"))
                {
                    tmpProd = tmpRow["fbillno"] != DBNull.Value ? tmpRow["fbillno"].ToString().Trim().Split('-')[0] : "";
                }

                if (tmpProd != null && tmpProd.Length > 0)
                {
                    SearchMaterialDetailForProdDia tmpDia = new SearchMaterialDetailForProdDia(tmpProd);
                    tmpDia.ShowDialog();
                }
                else
                {
                    UIMessageBox.ShowWarning("工单号为空，无法查询物料明细！");
                }
            }
            else
            {
                UIMessageBox.ShowWarning("请在列表中选择工单后再使用【查看工单明细】功能！");
            }
        }

        private void MtoNumber_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                PullingKingDeeDataRuleAndEvent();
            }
        }
    }
}
